package com.glsc.ngateway.platform.service.glres;

import cn.hutool.core.collection.CollectionUtil;
import com.glsc.ngateway.common.api.common.utils.PageUtil;
import com.glsc.ngateway.common.api.platform.dto.user.PlatformUserDto;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.glres.GlscResourceOperateLog;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.glres.GlscSystemAuth;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.glres.GlscSystemTeam;
import com.glsc.ngateway.common.base.repo.mysql.gateway.platform.glres.GlscSystemAuthRepository;
import com.glsc.ngateway.platform.service.UserService;
import com.glsc.ngateway.platform.utils.SpecificationUtil;
import com.google.common.collect.Lists;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

@Service
public class GlscSystemAuthService {

    @Resource
    private GlscSystemAuthRepository glscSystemAuthRepository;

    @Resource
    private UserService userService;

    @Resource
    private GlscResourceOperateLogService logService;

    /**
     * 分页查找
     *
     * @param pageNo
     * @param pageSize
     * @param param
     * @return
     */
    public Page<GlscSystemAuth> page(int pageNo, int pageSize, Map<String, Object> param) {
        Sort.Direction direction = Sort.Direction.DESC;
        String sort = "createTime";

        pageNo = PageUtil.initPageNo(pageNo);
        pageSize = PageUtil.initPageSize(pageSize);

        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, direction, sort);
        Page<GlscSystemAuth> page = glscSystemAuthRepository.findAll(SpecificationUtil.buildSpecification(param, GlscSystemAuth.class), pageable);
        return page;
    }

    /**
     * 根据系统id查找所有的对接方信息
     *
     * @param systemId
     * @return
     */
    public List<GlscSystemAuth> listBySystemId(Integer systemId) {
        return glscSystemAuthRepository.findAll(Example.of(GlscSystemAuth.builder().systemId(systemId).build()));
    }

    /**
     * 根据用户id查询所有系统权限信息
     *
     * @param userId
     * @return
     */
    public List<GlscSystemAuth> listByUserId(Long userId) {
        List<GlscSystemAuth> list = glscSystemAuthRepository.findAll(Example.of(GlscSystemAuth.builder().userId(userId).build()));
        if (CollectionUtil.isEmpty(list)) {
            return null;
        }
        List<GlscSystemAuth> resLis = Lists.newArrayList();

        for (GlscSystemAuth glscSystemAuth : list) {
            //长期有效
            if ("1".equals(glscSystemAuth.getValidityType())) {
                resLis.add(glscSystemAuth);
            } else {
                if (glscSystemAuth.getValidityDate().isAfter(LocalDate.now())) {
                    resLis.add(glscSystemAuth);
                }
            }
        }
        return resLis;
    }

    /**
     * 根据系统id和用户id查询权限信息
     *
     * @param systemId
     * @param oaAccount
     * @return
     */
    public List<GlscSystemAuth> listBySysIdAndUserOaAccount(Integer systemId, String oaAccount) {
        List<GlscSystemAuth> list = glscSystemAuthRepository.findAll(Example.of(GlscSystemAuth.builder().systemId(systemId).userOaAccount(oaAccount).build()));
        if (CollectionUtil.isEmpty(list)) {
            return null;
        }

        List<GlscSystemAuth> resLis = Lists.newArrayList();

        for (GlscSystemAuth glscSystemAuth : list) {
            //长期有效
            if ("1".equals(glscSystemAuth.getValidityType())) {
                resLis.add(glscSystemAuth);
            } else {
                if (glscSystemAuth.getValidityDate().isAfter(LocalDate.now())) {
                    resLis.add(glscSystemAuth);
                }
            }
        }
        return resLis;
    }


    /**
     * 根据id查找
     *
     * @param id
     * @return
     */
    public GlscSystemAuth findById(Integer id) {
        Optional<GlscSystemAuth> optional = glscSystemAuthRepository.findById(id);
        if (optional.isPresent()) {
            return optional.get();
        }
        return null;
    }

    /**
     * 保存
     *
     * @param obj
     * @return
     */
    @Transactional
    public GlscSystemAuth save(GlscSystemAuth obj) {

        PlatformUserDto user = userService.findByUsername(obj.getUserOaAccount());
        if (Objects.nonNull(user)) {
            obj.setUserId(user.getId());
            obj.setUserName(user.getName());
        }

        if ("2".equals(obj.getValidityType())) {
            Assert.isTrue(Objects.nonNull(obj.getValidityDate()), "有效期限截止日不可为空");
        }

        List<GlscSystemAuth> oldDatas = listBySysIdAndUserOaAccount(obj.getSystemId(), obj.getUserOaAccount());

        if (CollectionUtil.isNotEmpty(oldDatas) && oldDatas.get(0).getId() != obj.getId()) {
            Assert.isTrue(false, "该用户权限已经存在");
        }

        if ("1".equals(obj.getValidityType())) {
            obj.setValidityDate(null);
        }
        GlscSystemAuth auth = null;
        if (Objects.nonNull(obj.getId())) {
            auth = findById(obj.getId());
        }

        if (Objects.nonNull(auth)) {
            if (!obj.getValidityType().equals(auth.getValidityType()) || !obj.getUserName().equals(auth.getUserName())
                    || ("2".equals(auth.getValidityType()) && "2".equals(obj.getValidityType()) && !auth.getValidityDate().isEqual(obj.getValidityDate()))
                    || (StringUtils.isNotBlank(obj.getMemo()) && StringUtils.isBlank(auth.getMemo()))
                    || (StringUtils.isBlank(obj.getMemo()) && StringUtils.isNotBlank(auth.getMemo()))
                    || (StringUtils.isNotBlank(obj.getMemo()) && StringUtils.isNotBlank(auth.getMemo()) && !obj.getMemo().equals(auth.getMemo()))
            ) {
                logService.save(GlscResourceOperateLog.builder().deleted("N").memo(auth.getMemo()).content("权限变更[" + auth.getUserName() + "],权限类型为[" + ("1".equals(auth.getValidityType()) ? "长期有效" : "临时有效") + "]").
                        type("update_info").userId(auth.getUserId()).userName(auth.getUserName()).userOaAccount(auth.getUserOaAccount()).systemId(auth.getSystemId())
                        .originalCreateTime(auth.getCreateTime()).dataType("1").originalId(auth.getId()).build());
            }
        }

        return glscSystemAuthRepository.save(obj);
    }

    /**
     * 根据id删除
     *
     * @param id
     */
    @Transactional
    public void delete(Integer id) {
        GlscSystemAuth auth = findById(id);
        logService.save(GlscResourceOperateLog.builder().deleted("N").memo(auth.getMemo()).content("权限删除[" + auth.getUserName() + "],权限类型为[" + ("1".equals(auth.getValidityType()) ? "长期有效" : "临时有效") + "]").
                type("delete_info").userId(auth.getUserId()).userName(auth.getUserName()).userOaAccount(auth.getUserOaAccount())
                .originalCreateTime(auth.getCreateTime()).dataType("1").originalId(auth.getId()).systemId(auth.getSystemId()).build());
        glscSystemAuthRepository.deleteById(id);
    }
}
